package main

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"github.com/huannet/GinAdRoute/models"
	"time"
	"html/template"
)

var DB = make(map[string]string)


func formatAsDate(t time.Time) string {
	return "23"
}

func setupRouter() *gin.Engine {

	//gin.DisableConsoleColor()
	ge := gin.Default()
	ge.Use(gin.Logger())
	ge.Use(gin.Recovery())
	ge.Static("/assets", "./assets")
	ge.LoadHTMLGlob("templates/*")

	ge.SetFuncMap(template.FuncMap{
		"formatAsDate": formatAsDate,
	})

	ge.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "欢迎来到golang的世界！",
			"users": []models.User{
				models.User{Name: "chenshengwen", Email: "chenshengwen@huan.tv", LastLoginTime: time.Now(), Score:7.6},
				models.User{Name: "renliang", Email: "renliang@huan.tv", LastLoginTime: time.Now().AddDate(0,0, 30), Score: 7.7},
			},
			"comments": []models.Comment{
				models.Comment{ID:32,TargetModel:"Post",TargetId:1,UserId:1,Content:"这是我的评论1"},
				models.Comment{ID:33,TargetModel:"Post",TargetId:1,UserId:1,Content:"这是我的评论2"},
			},
		})
	})

	// Ping test
	ge.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	ge.POST("/loginJSON", func(c *gin.Context) {
		var json models.Login
		if err := c.BindJSON(&json); err == nil {
			// log.Println(json.User + "\t" + json.Password)
			if json.User == "superwen" && json.Password == "superwen@gmail.com" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		}
	})



	return ge
}

func main() {
	log.Println("start webserver")
	ge := setupRouter()
	ge.Run(":8080")
}